package com.foreveross.bsl.common.utils.balance.zookeeper;

import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;

import java.util.List;

/**
 * a Watcher for monitor zookeeper by getChildren 基本监听器
 *
 * @author heyaowen   Date:2014-10-16 14:39
 */
public abstract class ZooKeeperChildrenWatcher implements Watcher {

    private ZooKeeper zooKeeper;
    private String groupName;
    private GroupMemberCenter gmc = null;
    
    public ZooKeeperChildrenWatcher() {}
    public ZooKeeperChildrenWatcher(GroupMemberCenter gmc, String groupName) {
    	this.gmc = gmc;
    	this.groupName = groupName;
    }
    

    public void setZooKeeper(ZooKeeper zooKeeper) {
        this.zooKeeper = zooKeeper;
    }
    public void setGroupName(String groupName) {
        this.groupName = groupName;
    }
    
	public void init() {
        if (zooKeeper != null) {
            this.gmc = new GroupMemberCenter();
            this.gmc.setZooKeeper(zooKeeper); // 注入
            this.fetchAndUpdate();
        }
    }

    /** 执行回调
     * [updateData description]
     * @param members [description]
     */
    protected abstract void updateData(List<String> members);

    /** 获取此path最新数据，并且再次监听
     * [fetchAndUpdate description]
     */
    private void fetchAndUpdate() {
        // get children and register watcher again 默认只会监听一次，这里回调时再监听 --> 设置永久监听
        List<String> members = this.gmc.fetchGroupMembers(groupName, this);
        this.updateData(members);
    }

    @Override
    public void process(WatchedEvent event) {
        this.fetchAndUpdate();
    }
}
